package com.coolweather.android;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import com.coolweather.android.db.City;
import com.coolweather.android.db.County;
import com.coolweather.android.db.Province;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private Button button1, button2, button3, button4, button5;
    private ArrayAdapter<String> adapter;
    private List<String> dataList = new ArrayList<>();
    private List<Province> provinceList;
    private List<City> cityList;
    private List<County> countyList;
    private ListView list;
    private Province selectedProvince;
    private City selectedCity;
    public static final int LEVEL_PROVINCE=0;
    public static final int LEVEL_CITY=1;
    public static final int LEVEL_COUNTY=2;
    private int currentLevel;
    ImageView getData,back;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        if (prefs.getString("weather", null) != null){
            Intent intent = new Intent(this, WeatherActivity.class);
            startActivity(intent);
            finish();
        }


        /*getData = findViewById(R.id.getData);
        getData.setOnClickListener((View.OnClickListener) this);

        list = (ListView) findViewById(R.id.listview);
        adapter = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,dataList);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                if (currentLevel==LEVEL_PROVINCE) {
                    Log.d("level", String.valueOf(position));
                    Log.d("info", provinceList.get(position).getProvinceName());
                    selectedProvince = provinceList.get(position);
                    int provinceCode = selectedProvince.getProvinceCode();
//                    String url = "http://guolin.tech/api/china/" + provinceCode;
//                    getDataThread(url, "city");
                    displayCityData();
                }else if (currentLevel==LEVEL_CITY){
                    Log.d("level","level enter city");
                    selectedCity = cityList.get(position);
                    int cityCode = selectedCity.getCityCode();
                    displayCountyData();
                }
                else if (currentLevel==LEVEL_COUNTY){
                    Log.d("level","level enter COUNTY");
//                    displayCountyData();
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                    if (prefs.getString("weather", null) != null){
                    String weatherId=countyList.get(position).getWeatherId();
                    Intent intent=new Intent(MainActivity.this,WeatherActivity.class);
                    intent.putExtra("weather_id",weatherId);
                    startActivity(intent);
                    MainActivity.this.finish();}
                }
            }
        });

        back = findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentLevel==LEVEL_CITY){
                    Log.d("level","level back into province");
                    displayProvincesData();
                }
                else if (currentLevel==LEVEL_COUNTY){
                    Log.d("level","level back into city");
                    displayCityData();

                }
            }
        });

        createdatabase();
//        DataSupport.deleteAll(Province.class);
//        DataSupport.deleteAll(City.class);
//        DataSupport.deleteAll(County.class);
        displayProvincesData();*/

    }
/*

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.getData:
                Log.d("获取了网络数据", "获取了网络数据");
//                reqData();
//                displayProvincesData();
                getDataThread("http://guolin.tech/api/china","province");

                break;
            default:
                break;
        }

    }

*/
/*
    void provincesave() {
//        String sql="INSERT INTO Province VALUES()";
        Province province = new Province();
        province.setId(1);
        province.setProvinceName("四川");
        province.setProvinceCode(111);
        province.save();

    }

    void citysave() {
        City city = new City();
        city.setId(2);
        city.setCityName("自贡");
        city.setCityCode(2);
        city.setProvinceId(222);
        city.save();

    }

    void countrysave() {
        County county = new County();
        county.setId(3);
        county.setCountyName("荣县");
        county.setWeatherId("26");
        county.setCityId(3);
        county.save();
    }
*/
    /*



    public void createdatabase(){
        Connector.getDatabase();
    }

    //线程
    private void getDataThread(String address, String type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(address).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();//获取数据   resp的数据放在body
                    if ("province".equals(type)) {
                        parseProvincedata(responseData);//解析数据
                    }else if("city".equals(type)){
                        parseCitydata(responseData);
                    }
                    else if ("county".equals(type)){
                        parseCountydata(responseData);
                    }
                    Log.d("info", responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public void parseProvincedata(String data) throws JSONException {

        JSONArray allProvinces = new JSONArray(data);
        for (int i = 0; i < allProvinces.length(); i++) {
            JSONObject provinceObject = allProvinces.getJSONObject(i);
            String ProvinceName = provinceObject.getString("name");
            int ProvinceCode = provinceObject.getInt("id");
            Log.d("infoProvinceName", ProvinceName);
            Province province = new Province();
//            province.setId(ProvinceCode);
            province.setProvinceName(ProvinceName);
            province.setProvinceCode(ProvinceCode);
            province.save();
        }


    }

    public void parseCitydata(String data) throws JSONException {

        JSONArray allCity = new JSONArray(data);
        int provinceCode=selectedProvince.getProvinceCode();
        for (int i = 0; i < allCity.length(); i++) {
            JSONObject cityObject = allCity.getJSONObject(i);
            String CityName = cityObject.getString("name");
            int CityCode = cityObject.getInt("id");
            Log.d("infoCityName", CityName);
            City city = new City();
            city.setId(CityCode);
            city.setCityName(CityName);
            city.setProvinceId(provinceCode);
            city.setCityCode(CityCode);
            city.save();
        }


    }

    public void parseCountydata(String data) throws JSONException {

        JSONArray allCounty = new JSONArray(data);
        int cityCode=selectedCity.getCityCode();
        for (int i = 0; i < allCounty.length(); i++) {
            JSONObject countyObject = allCounty.getJSONObject(i);
            String countyName = countyObject.getString("name");
            int countyCode = countyObject.getInt("id");
            String weatherId=countyObject.getString("weather_id");
            Log.d("infocountyName", countyName);
            County county = new County();
            county.setCountyName(countyName);
            county.setCityId(cityCode);
            county.setId(countyCode);
            county.setWeatherId(weatherId);
            county.save();
        }


    }


    public  void displayProvincesData() {
        provinceList = DataSupport.findAll(Province.class);
        if (provinceList.size() > 0) {
            dataList.clear();
            for (Province province : provinceList) {
                Log.d("provinceinfo",province.getProvinceName());
                dataList.add(province.getProvinceName());
            }
            adapter.notifyDataSetChanged();
            currentLevel=LEVEL_PROVINCE;
        }else{
            String url = "http://guolin.tech/api/china";
            getDataThread(url, "province");
        }

    }

    public void displayCityData() {
        int provinceCode=selectedProvince.getProvinceCode();
        cityList = DataSupport.where("provinceid=?",String.valueOf(provinceCode)).find(City.class);
        if (cityList.size() > 0) {
            dataList.clear();
            for (City city : cityList) {
//                Log.d("cityinfo",city.getCityName());
                dataList.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            currentLevel=LEVEL_CITY;
        }else{
            String url = "http://guolin.tech/api/china/"+provinceCode;
            getDataThread(url, "city");
        }

    }

    private void displayCountyData() {
        int cityCode=selectedCity.getCityCode();
        countyList = DataSupport.where("cityid=?",String.valueOf(cityCode)).find(County.class);
        if (countyList.size() > 0) {
            dataList.clear();
            for (County county : countyList) {
//                Log.d("countyinfo",county.getCountyName());
                dataList.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            currentLevel=LEVEL_COUNTY;
        }else{
            int provinceCode=selectedProvince.getProvinceCode();
            String url = "http://guolin.tech/api/china/"+provinceCode+"/"+cityCode;
            getDataThread(url, "county");
        }

    }
*/

}

